# Assistente de Compras.
import e32db
import appuifw

'''
    DAO
'''
class DAO:

    def __init__(self, dbpath):
        self.db = e32db.Dbms()
        self.dbv = e32db.Db_view()
        self.reset_counters()
        try:
            self.db.open(unicode(dbpath))
        except:
            self.db.create(unicode(dbpath))
            self.db.open(unicode(dbpath))
            self.query("create table listaProdutos (id COUNTER, data DATE)")
            self.query("create table dieta (id COUNTER, nome VARCHAR, quantidade INTEGER, dia INTEGER)")


    def reset_counters(self):
        self.affected_rows = 0
        self.num_rows = 0
        self.__internal_counter = 0

    def query(self, sql):
        self.reset_counters()
        if sql.lower().startswith('select'):
            self.dbv.prepare(self.db, unicode(sql))
            self.dbv.first_line()
            self.num_rows = self.dbv.count_line()
        else:
            self.affected_rows = self.db.execute(unicode(sql))
            
            if self.affected_rows is None:
                appuifw.note(u'Problema ao salvar os dados.', 'error')

    def next(self):
        row = {'id': 0}
        if self.num_rows < 1:
            self.reset_counters()
            raise StopIteration
        elif self.__internal_counter < self.num_rows:
            self.dbv.get_line()
            for i in range(self.dbv.col_count()):
                row[i] = self.dbv.col(i+1)
            self.dbv.next_line()
            self.__internal_counter += 1
            return row
        else:
            self.reset_counters()
            raise StopIteration


    def __iter__(self):
        return self

    def getLastId(self, table):
        self.dbv.prepare(self.db, u"SELECT id FROM " + table + " ORDER BY id DESC")
        self.dbv.first_line()
        self.dbv.get_line()
        last_id = self.dbv.col(1)
        return last_id